# -*- coding: utf-8 -*-
import pymysql.cursors

from famousbook.chapter_items import ChapterItem
from famousbook.items import FamousbookItem
from famousbook.settings import mysql_host, mysql_port, mysql_user, mysql_password, mysql_db_name


# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html


class FamousbookPipeline(object):
    def __init__(self):
        self.connect = pymysql.connect(
            host=mysql_host,  # 数据库地址
            port=mysql_port,  # 数据库端口
            db=mysql_db_name,  # 数据库名
            user=mysql_user,  # 数据库用户名
            passwd=mysql_password,  # 数据库密码
            charset='utf8',  # 编码方式
            use_unicode=True)

        # 通过cursor执行增删查改
        self.cursor = self.connect.cursor()

    def process_item(self, item, spider):
        if isinstance(item, FamousbookItem):
            self.cursor.execute(
                "insert into book(book_id, book_type, book_name, author, introduce) values(%s, %s, %s, %s, %s)",
                (item['book_id'],  # item里面定义的字段和表字段对应
                 item['book_type'],
                 item['book_name'],
                 item['author'],
                 item['introduce']))
        elif isinstance(item, ChapterItem):
            self.cursor.execute("insert into chapter(book_id, title, content) values(%s, %s, %s)",
                                (item['book_id'],  # item里面定义的字段和表字段对应
                                 item['title'],
                                 item['content']))

        self.connect.commit()
        return item
